package com.br.android.widing;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.br.android.widing.db.WidingCategoriaDAO;
import com.br.android.widing.entity.Categoria;

public class EditarCategoriaActivity extends SherlockActivity {

	private EditText etDescricao;

	private int idCat;

	WidingCategoriaDAO dao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_edit_categoria);

		etDescricao = (EditText) findViewById(R.id.edDescricao);

		dao = new WidingCategoriaDAO(this);

		Intent intent = getIntent();
		idCat = intent.getExtras().getInt("id");
		etDescricao.setText(intent.getExtras().getString("descricao"));

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_edicao_categoria, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_edicao_categoria_xml:
			Categoria cat = new Categoria();
			cat.setIdcategoria(idCat);
			if (etDescricao.getText().toString().trim().equals("")) {
				Toast.makeText(this, "Informe a descri\u00e7\u00e3o para a categoria.",
						Toast.LENGTH_SHORT).show();
				return super.onOptionsItemSelected(item);
			}
			cat.setNomecategoria(etDescricao.getText().toString());
			dao.alterarCategoria(cat);
			dao.close();
			startActivity(new Intent(this, PrincipalActivity.class));
			overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
			finish();
			Toast.makeText(this, "Categoria alterada com sucesso.",
					Toast.LENGTH_SHORT).show();
			break;
		default:
			startActivity(new Intent(this, PrincipalActivity.class));
			overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(new Intent(this, PrincipalActivity.class));
			overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
}
